// pages/shopDetail/shopDetail.ts
const apidecr = require('../../api/request')
interface Item {
  category_name: ''
  shop_name: ''
}
interface obj {
  goods_id: ''
  goods_img: ''
  goods_name: ''
  goods_price: number,
  quantity: number
}
interface Obj1 {
  goods_id: string;
  goods_img: string;
  goods_name: string;
  goods_price: string;
}

// 假设你的数据结构如下
interface DataSet {
  goods_id: string;
  currentgoods: Obj1[];
}
Page({


  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    activeIndex: 0,
    goodArr: '',
    isClick: false,
    clikGoods: [],
    isAdd: false,
    // 放大框添加
    addNum1: 0,
    addArr: [] as obj[],
    isadd1: false,
    addNumMap: {},

    // 购物车添加数量及已选数量
    addTotal: [] as obj[],
    carnum: 0,
    // 已选
    seleted: 0,
    // 应付的价钱
    tatol: 0,
    // 配送费
    cost: 0
  },


  jumpcheck(){
    const { addArr, cost, tatol } = this.data;
    // 存储最后一次的数据
    wx.setStorageSync('addArr', addArr);
    wx.setStorageSync('seleted', addArr.length);
    wx.setStorageSync('cost', cost);
    wx.setStorageSync('tatol', tatol);
    // ../pages/check/check
    wx.navigateTo({
      url: '../check/check'
    })
  },
  async shopgetFn(shop_id: string) {
    const content: any = await apidecr.shopget()
    // console.log(content)
    if (content.code == 200) {
      const shoparr = content.content.map((item: Sitem) => {
        return {
          shop_id: item.shop_id,
          shop_name: item.shop_name,
          category_name: item.category_name,
          shop_img: item.shop_img
        }
      })
      // console.log(shoparr)
      const titles = shoparr
        .filter((item: Item) => shop_id == item.shop_id) // 筛选出匹配的项
        .map((item: Item) => ({
          category_name: item.category_name,
          shop_name: item.shop_name
        }));
      // console.log('标题：', titles)
      let [{ category_name, shop_name }] = titles
      // console.log(category_name)
      this.setData({
        title: category_name + ' - ' + shop_name
      })
      return shoparr
    }
    return []

  },
  changeActive: function (event: any) {
    const index = event.currentTarget.dataset.index
    this.setData({
      activeIndex: index
    })
  },
  async goodFn(shop_id: any) {
    const content = await apidecr.goodget()
    // console.log(content)
    if (content.code == 200) {
      const goodsArr = content.content.filter((item: { shop_id: any }) => {
        return shop_id == item.shop_id
      })
      // console.log("goodsArr1：",goodsArr)
      this.setData({
        goodArr: goodsArr
      })
      return goodsArr
    }
  },

  

  // 点击添加
  clickPlusFn(event: any) {
    const isadd = event.currentTarget.dataset.goods_id;
    const currentgoods = event.currentTarget.dataset.currentgoods;
    // console.log('111:', currentgoods)

    // 找到当前商品信息
    const goodsmess = currentgoods.find((item: obj) => item.goods_id === isadd);

    // 增加当前商品的数量
    goodsmess.quantity++;

    // 更新数据
    this.setData({
      goodArr: currentgoods,
      goodIndex: currentgoods,
      isClick: false
    },() => {
      console.log('isClick 当前值:', this.data.isClick); // 确认更新后的值
    });

    const newArr: obj[] = this.data.addArr || [];

    // 查找数量不为零的商品
    const nozero = currentgoods.filter((item: obj) => item.quantity > 0);
    // console.log({ nozero });

    if (nozero.length > 0) { // 确保有商品
      const nozeroid = nozero.map((item: { goods_id: any }) => item.goods_id);
      // console.log({ nozeroid });

      // 检查 newArr 中是否存在与 nozeroid 中相同的 goods_id
      const existingItems = newArr.filter((item: { goods_id: any }) => nozeroid.includes(item.goods_id));
      const existingIds = existingItems.map(item => item.goods_id);
      // console.log({ existingItems, existingIds });

      // 只添加不在 existingIds 中的商品
      const itemsToAdd = nozero.filter((item: { goods_id: any }) => {
        // 确保类型一致
        return !existingIds.includes(item.goods_id);
      });
      const nowprice1 = nozero.map((item: { goods_id: any; quantity: number }) => {
        return {
          goods_id: item.goods_id,
          quantity: item.quantity
        }
      })
      newArr.forEach((item) => {
        // 查找 nowprice1 中对应的商品
        const matchingItem = nowprice1.find((item1: { goods_id: string }) => item1.goods_id === item.goods_id);
        // 如果找到了匹配的商品，则更新 quantity
        if (matchingItem) {
          item.quantity = matchingItem.quantity; // 更新 quantity
        }
      });
      if (itemsToAdd.length > 0) {
        newArr.push(...itemsToAdd); // 添加新商品
        // console.log('添加商品:', itemsToAdd); // 确认添加的商品
      } else {
        console.log('所有商品 ID 已存在，未重复添加。', existingIds);
      }
    } else {
      console.log('没有数量不为零的商品');
    }
    const price = newArr.map((item) => {
      return {
        goods_price: item.goods_price,
        quantity: item.quantity
      }
    })
    // console.log({ price })
    const totalPrice = parseFloat(price.reduce((accumulator, item) => {
      return accumulator + (item.goods_price * item.quantity);
    }, 0).toFixed(2));

    // console.log(totalPrice); // 输出总价格

    // 更新数据
    // console.log({ newArr });
    if (newArr.length > 0) {
      this.data.cost = 3
    }
    // console.log({ newArr })
    this.setData({
      addArr: newArr,
      seleted: newArr.length,
      cost: this.data.cost,
      tatol: totalPrice,
    });
  },

  clickPlusFn1(event: any) {
    const isadd = event.currentTarget.dataset.goods_id;
    const currentgoods = event.currentTarget.dataset.currentgoods;
    // console.log('currentgoods:',currentgoods)
    // 所有商品的
    const allgoods = event.currentTarget.dataset.allgoods
    // console.log('allgoods:', allgoods)
    // 找到当前商品信息
    const goodsmess = currentgoods.find((item: obj) => item.goods_id === isadd);
    // 增加当前商品的数量
    goodsmess.quantity++;
    const allnum1 = allgoods.find((item: obj) => item.goods_id === isadd)
    if (allnum1) {
      allnum1.quantity = goodsmess.quantity;
      // console.log("更新后的 allgoods 中数量：", allnum1.quantity);
    }
    // console.log("数量：", goodsmess.quantity)
    // 更新数据
    this.setData({
      goodIndex: currentgoods,
      goodArr: allgoods,
    });
    const newArr: obj[] = this.data.addArr || [];

    // 查找数量不为零的商品
    const nozero = currentgoods.filter((item: obj) => item.quantity > 0);
    // console.log({ nozero });

    if (nozero.length > 0) { // 确保有商品
      const nozeroid = nozero.map((item: { goods_id: any }) => item.goods_id);
      // console.log({ nozeroid });

      // 检查 newArr 中是否存在与 nozeroid 中相同的 goods_id
      const existingItems = newArr.filter((item: { goods_id: any }) => nozeroid.includes(item.goods_id));
      const existingIds = existingItems.map(item => item.goods_id);
      // console.log({ existingItems, existingIds });

      // 只添加不在 existingIds 中的商品
      const itemsToAdd = nozero.filter((item: { goods_id: any }) => {
        // 确保类型一致
        return !existingIds.includes(item.goods_id);
      });
      const nowprice1 = nozero.map((item: { goods_id: any; quantity: number }) => {
        return {
          goods_id: item.goods_id,
          quantity: item.quantity
        }
      })
      newArr.forEach((item) => {
        // 查找 nowprice1 中对应的商品
        const matchingItem = nowprice1.find((item1: { goods_id: string }) => item1.goods_id === item.goods_id);
        // 如果找到了匹配的商品，则更新 quantity
        if (matchingItem) {
          item.quantity = matchingItem.quantity; // 更新 quantity
        }
      });
      if (itemsToAdd.length > 0) {
        newArr.push(...itemsToAdd); // 添加新商品
        // console.log('添加商品:', itemsToAdd); // 确认添加的商品
      } else {
        console.log('所有商品 ID 已存在，未重复添加。', existingIds);
      }
    } else {
      console.log('没有数量不为零的商品');
    }
    const price = newArr.map((item) => {
      return {
        goods_price: item.goods_price,
        quantity: item.quantity
      }
    })
    // console.log({ price })
    const totalPrice = parseFloat(price.reduce((accumulator, item) => {
      return accumulator + (item.goods_price * item.quantity);
    }, 0).toFixed(2));

    // console.log(totalPrice); // 输出总价格

    // 更新数据
    // console.log({ newArr });
    if (newArr.length > 0) {
      this.data.cost = 3
    }
    // console.log({ newArr })
    this.setData({
      addArr: newArr,
      seleted: newArr.length,
      cost: this.data.cost,
      tatol: totalPrice
    });


  },

  // 点击减少
  clickminuFn(event: any) {
    const isadd = event.currentTarget.dataset.goods_id;
    const currentgoods = event.currentTarget.dataset.currentgoods;


    // 找到当前商品信息
    const goodsmess = currentgoods.find((item: obj) => item.goods_id === isadd);

    // 减少当前商品的数量
    goodsmess.quantity--;
    if (goodsmess.quantity < 0) {
      goodsmess.quantity = 0;
    }

    // 更新数据
    this.setData({
      goodArr: currentgoods, // 确保更新原始商品数组
      goodIndex: currentgoods, // 同步更新
      isClick: false
    });

    let newArr: obj[] = this.data.addArr || [];
    // console.log({newArr})
    const newgoods = newArr.map((item)=>{
      return {
        goods_id: item.goods_id,
        quantity: item.quantity
      }
    })

    // 查找需要减少数量的商品
    const curgoods = currentgoods.map((item: { goods_id: any; quantity: any }) => {
      return {
        goods_id: item.goods_id,
        quantity: item.quantity
      };
    }); 
    
    const curgoodsId = curgoods.map((item: { goods_id: any }) => item.goods_id);
    // console.log({ curgoods });
    
    // 查找与 curgoodsId 匹配的新商品
    const newId = newgoods.filter((item) => curgoodsId.includes(item.goods_id));
    
    // 如果找到匹配的新商品，更新 newArr 中的数量
    if (newId.length > 0) {
      newId.forEach((newItem) => {
        // 找到 newArr 中对应的商品
        const existingItem = newArr.find((item) => item.goods_id === newItem.goods_id);
        
        // 如果找到了，更新数量
        if (existingItem) {
          const curItem = curgoods.find((item: { goods_id: string }) => item.goods_id === newItem.goods_id);
          if (curItem) {
            existingItem.quantity = curItem.quantity; // 更新数量
            if (existingItem.quantity <= 0) {
              newArr = newArr.filter(item => item.goods_id != existingItem.goods_id);
            }
          }
        }
      });
    }
    // console.log({newArr})



     // 计算总价格
    const price = newArr.map((item) => {
      return {
        goods_price: item.goods_price,
        quantity: item.quantity
      };
    });

    const totalPrice = parseFloat(price.reduce((accumulator, item) => {
      return accumulator + (item.goods_price * item.quantity);
    }, 0).toFixed(2));
    // console.log(newArr.length)

    // // // 更新数据
    if (newArr.length <= 0) {
      this.data.cost = 0; 
    }

    this.setData({
      addArr: newArr,
      seleted: newArr.length,
      cost: this.data.cost,
      tatol: totalPrice,
      isClick: false
    });

  },

  clickminuFn1(event: any) {
    const isadd = event.currentTarget.dataset.goods_id;
    const currentgoods = event.currentTarget.dataset.currentgoods;
    const allgoods = event.currentTarget.dataset.allgoods

    // 找到当前商品信息
    const goodsmess = currentgoods.find((item: obj) => item.goods_id === isadd);

    // 减少当前商品的数量
    goodsmess.quantity--;
    const allnum1 = allgoods.find((item: obj) => item.goods_id === isadd)
    if (allnum1) {
      allnum1.quantity = goodsmess.quantity;
      // console.log("更新后的 allgoods 中数量：", allnum1.quantity);
    }
    if (goodsmess.quantity < 0) {
      goodsmess.quantity = 0;
    }

    // 更新数据
    this.setData({
      goodArr: allgoods, // 确保更新原始商品数组
      goodIndex: currentgoods // 同步更新
    });
    let newArr: obj[] = this.data.addArr || [];
    // console.log({newArr})
    const newgoods = newArr.map((item)=>{
      return {
        goods_id: item.goods_id,
        quantity: item.quantity
      }
    })

    // 查找需要减少数量的商品
    const curgoods = currentgoods.map((item: { goods_id: any; quantity: any }) => {
      return {
        goods_id: item.goods_id,
        quantity: item.quantity
      };
    }); 
    
    const curgoodsId = curgoods.map((item: { goods_id: any }) => item.goods_id);
    // console.log({ curgoods });
    
    // 查找与 curgoodsId 匹配的新商品
    const newId = newgoods.filter((item) => curgoodsId.includes(item.goods_id));
    
    // 如果找到匹配的新商品，更新 newArr 中的数量
    if (newId.length > 0) {
      newId.forEach((newItem) => {
        // 找到 newArr 中对应的商品
        const existingItem = newArr.find((item) => item.goods_id === newItem.goods_id);
        
        // 如果找到了，更新数量
        if (existingItem) {
          const curItem = curgoods.find((item: { goods_id: string }) => item.goods_id === newItem.goods_id);
          if (curItem) {
            existingItem.quantity = curItem.quantity; // 更新数量
            if (existingItem.quantity <= 0) {
              newArr = newArr.filter(item => item.goods_id != existingItem.goods_id);
            }
          }
        }
      });
    }
    // console.log({newArr})



     // 计算总价格
    const price = newArr.map((item) => {
      return {
        goods_price: item.goods_price,
        quantity: item.quantity
      };
    });

    const totalPrice = parseFloat(price.reduce((accumulator, item) => {
      return accumulator + (item.goods_price * item.quantity);
    }, 0).toFixed(2));
    // console.log(newArr.length)

    // // // 更新数据
    if (newArr.length <= 0) {
      this.data.cost = 0; 
    }

    this.setData({
      addArr: newArr,
      seleted: newArr.length,
      cost: this.data.cost,
      tatol: totalPrice
    });
    
  },

  // 加入购物车
  addCarFn(event: any) {
    const isadd = event.currentTarget.dataset.goods_id;
    const currentgoods = event.currentTarget.dataset.currentgoods;
    const newArr: obj[] = this.data.addTotal || []
    const digarr = newArr.find((item: obj) => item.goods_id == isadd)
    // console.log({ digarr })
    const goodsId = digarr ? digarr.goods_id : null;
    if (goodsId != isadd) {
      newArr.push(currentgoods[0])
    }
    this.setData({
      addTotal: newArr,
      carnum: newArr.length
    })
  },

  isClickFn(event: any) {
    // console.log(event)
    const goodsIndex: string = event.currentTarget.dataset.goods_id
    const goodIndex = this.data.goodArr;
    if (Array.isArray(goodIndex)) {
      const isClick = goodIndex.filter((item: { goods_id: string }) => {
        return goodsIndex == item.goods_id
      })
      this.setData({
        goodIndex: isClick,
        isClick: true
      })
    }
    else {
      console.error('goodIndex 不是数组:', goodIndex);
      return; // 如果不是数组，则退出
    }

    // isClick = true

  },


  closeFn() {
    this.setData({
      isClick: false,
      goodIndex: []
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    const shop_id: any = options.shop_id
    // console.log("页面：", shop_id)
    this.shopgetFn(shop_id)
    this.goodFn(shop_id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})